<template>

  <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="150px">
    <el-card>

      <el-row :gutter="20" type="flex" style="flex-wrap:wrap; flex-direction: row">

        <el-col :span="12">
          <el-form-item label="试题类型 " prop="quType">
            <dic-list-select v-model="postForm.quType" :disabled="update" :excludes="excludeTypes" dic-code="qu_type" title="请选择题型" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="12">
          <el-form-item label="所属题库" prop="repoId">
            <repo-select v-model="postForm.repoId" @code="repoChange" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="12">
          <el-form-item label="难度等级 " prop="quLevel">
            <dic-list-select v-model="postForm.quLevel" dic-code="qu_level" title="请选择难度等级" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="12">
          <el-form-item label="所属章节">
            <chapter-select v-model="postForm.chapterId" :repo-id="postForm.repoId" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="试题内容" prop="content">
            <Tinymce ref="content" v-model="postForm.content" :height="200" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="24">
          <el-form-item label="知识点">
            <key-point-select v-model="postForm.pointList" :root="pointRoot"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="整题解析" prop="oriPrice">
            <Tinymce ref="analysis" v-model="postForm.analysis" :height="200" />
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if="postForm.quType && (postForm.quType==='radio' || postForm.quType==='multi' || postForm.quType==='multi2' || postForm.quType==='judge' || postForm.quType==='fill')" class="filter-container" style="margin-top: 25px">

        <div style="margin-bottom: 10px">
          <el-button :disabled="postForm.answerList && postForm.answerList.length >= 8 || (postForm.quType==='judge' && postForm.answerList && postForm.answerList.length>=2)" class="filter-item" type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd">
            添加选项
          </el-button>
        </div>


        <div v-if="postForm.quType==='multi' || postForm.quType==='multi2'" class="qt-alert">
          <el-checkbox v-model="postForm.pathScore">漏选给分</el-checkbox>
          <div v-if="postForm.pathScore" style="padding-left: 10px">漏选也给分，请在下表配置每项得分比例！</div>
        </div>

        <div v-if="postForm.quType==='fill'" class="qt-alert">
          <el-checkbox v-model="postForm.pathScore" style="margin-left: 10px">按空给分</el-checkbox>
          <div v-if="postForm.pathScore" style="padding-left: 10px">每个空独立设置得分比例，答对就给分，请在下表配置每空得分比例！</div>
        </div>


        <el-table
          :data="postForm.answerList"
          :border="true"
          row-key="id"
          style="width: 100%;"
        >

          <el-table-column
            label="序号"
            width="100"
            align="center"
          >
            <template v-slot="scope">
              第{{ scope.$index+1 }}项
            </template>

          </el-table-column>

          <el-table-column
            v-if="itemIsAnswer && postForm.quType!=='fill'"
            label="是否答案"
            width="100"
            align="center"
          >
            <template v-slot="scope">
              <el-checkbox v-model="scope.row.isRight" @change="answerChange(scope.$index)">答案</el-checkbox>
            </template>

          </el-table-column>

          <el-table-column
            v-if="itemImage && postForm.quType!=='fill'"
            label="选项图片"
            width="160px"
            align="center"
          >
            <template v-slot="scope">

              <file-upload
                v-model="scope.row.image"
                :limit="1"
                :list-type="'picture-card'"
                :compress="500"
                accept=".jpg,.jpeg,.png"/>

            </template>
          </el-table-column>

          <el-table-column
            label="选项内容"
          >
            <template v-slot="scope">
              <el-input v-if="postForm.quType!=='fill'" v-model="scope.row.content" placeholder="输入选项内容" size="small" type="textarea" />
              <fill-item-editor v-else v-model="scope.row.content" />
            </template>
          </el-table-column>

          <el-table-column
            v-if="(postForm.quType==='multi' || postForm.quType==='multi2' || postForm.quType==='fill') && postForm.pathScore"
            width="160px"
            align="center"
            label="得分比例%">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.scoreRate" :disabled="postForm.quType!=='fill' && (scope.row.isRight==null || !scope.row.isRight)" :min="0" :max="100" size="mini" />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeItem(scope.$index, $event)" />
            </template>
          </el-table-column>

        </el-table>

        <div v-if="postForm.quType==='fill'" style="margin-top: 10px">
          <el-checkbox v-model="postForm.answerOrder" label="严格按序作答"/>
        </div>

      </div>

      <div v-if="postForm.quType && postForm.quType==='saq'" class="filter-container" style="margin-top: 25px">

        <div style="margin-bottom: 10px">
          <el-button :disabled="postForm.answerList && postForm.answerList.length >= 8" class="filter-item" type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd">
            添加关键字
          </el-button>
          <el-checkbox v-model="postForm.manual" style="margin-left: 10px">人工批阅/AI批阅</el-checkbox>
        </div>

        <el-table
          :data="postForm.answerList"
          :border="true"
          row-key="id"
          style="width: 100%;"
        >

          <el-table-column
            label="关键字">
            <template v-slot="scope">
              <fill-item-editor v-model="scope.row.content" placeholder="输入判分关键字" />
            </template>
          </el-table-column>

          <el-table-column
            width="160px"
            label="得分比例%">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.scoreRate" :min="0" :max="100" size="mini" />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeItem(scope.$index, $event)" />
            </template>
          </el-table-column>

        </el-table>

      </div>

    </el-card>

  </el-form>
</template>

<script>
import FillItemEditor from '@/components/FillItemEditor/index.vue'
import KeyPointSelect from '@/components/KeyPointSelect/index.vue'
import ChapterSelect from '@/components/ChapterSelect/index.vue'

export default {
  name: 'QuItemSave',
  components: { ChapterSelect, KeyPointSelect, FillItemEditor },
  props: {
    value: Object,
    child: {
      type: Boolean,
      default: false
    },
    update: Boolean,
    excludeTypes: Array
  },
  data() {
    return {

      lastId: '',

      initContent: false,
      initAnalysis: false,

      // 不同题型的显示项目
      itemImage: true,
      itemIsAnswer: true,

      // 初始化表单数据
      postForm: {
        quType: '',
        repoId: '',
        manual: true,
        answerList: []
      },
      rules: {
        content: [
          { required: true, message: '试题内容不能为空！' }
        ],

        quType: [
          { required: true, message: '试题类型不能为空！' }
        ],

        quLevel: [
          { required: true, message: '必须选择难度等级！' }
        ],

        repoId: [
          { required: true, message: '请选择题库！' }
        ]
      },
      pointRoot: null
    }
  },
  watch: {
    value: {
      handler(val) {
        this.fillValue(val.id !== this.lastId)
      },
      deep: true
    },

    // 变换题型
    'postForm.quType': {
      handler(val) {
        // 添加模式允许改题型
        if (!this.update) {
          this.handleTypeChange(val)
        }
      }
    },
    postForm: {
      handler(val) {
        this.$emit('input', val)
        this.$emit('change', val)
      },
      deep: true
    }
  },

  created() {
    this.fillValue(true)
  },
  mounted() {
    // 伪等待
    this.$nextTick(() => {
      setTimeout(() => {
        this.$emit('loaded', true)
      }, 2000)
    })
  },
  methods: {

    // 填充数据
    fillValue(init) {
      if (this.value) {
        this.postForm = this.value
        // 初始化
        this.initValue(init)
      } else {
        this.postForm = {}
      }

      if (!this.postForm.manual) {
        this.$set(this.postForm, 'manual', false)
      }
    },

    repoChange(v) {
      this.pointRoot = v.pointCode
    },

    // 添加时选择题型做对应的智能填充
    handleTypeChange(v) {
      // 填空题和组合题
      if (v === 'fill' || v === 'mix') {
        this.itemImage = false
        this.itemIsAnswer = false
      } else {
        this.itemImage = true
        this.itemIsAnswer = true
      }

      // 清空并填充
      this.postForm.answerList = []
      if (v === 'judge') {
        this.postForm.answerList.push({ isRight: true, content: '正确' })
        this.postForm.answerList.push({ isRight: false, content: '错误' })
      }

      // 单选多选默认
      if (v === 'multi' || v === 'multi2' || v === 'radio') {
        for (let i = 0; i < 4; i++) {
          this.postForm.answerList.push({ isRight: false, content: '' })
        }
      }

      // 简答题默认人工阅卷
      if (v === 'saq') {
        this.postForm.manual = true
      }

      // 填空题
      if (v === 'fill') {
        for (let i = 0; i < 2; i++) {
          this.postForm.answerList.push({ isRight: false, content: '', tagList: [], tagVisible: false, tagInput: '' })
        }
      }
    },

    // 添加子项
    handleAdd() {
      if (this.postForm.quType === 'saq') {
        this.postForm.manual = false
      }

      if (!this.postForm.answerList) {
        this.$set(this.postForm, 'answerList', [])
      }

      if (this.postForm.quType === 'fill') {
        this.postForm.answerList.push({ isRight: false, content: '', tagList: [], tagVisible: false, tagInput: '' })
        return
      }

      this.postForm.answerList.push({ isRight: false, content: '' })
    },

    removeItem(index) {
      this.postForm.answerList.splice(index, 1)
    },

    async initValue(init) {
      // 填空题不需要那些东西
      if (this.postForm.quType === 'fill') {
        this.itemImage = false
        this.itemIsAnswer = false
      } else {
        this.itemImage = true
        this.itemIsAnswer = true
      }

      // 试题发生变化，重新赋值
      if (init) {
        // 赋值
        this.lastId = this.postForm.id
      }
    },

    // 单选题互斥不选定多个
    answerChange(index) {
      // 类型
      if (this.postForm && (this.postForm.quType === 'radio' || this.postForm.quType === 'judge')) {
        for (let i = 0; i < this.postForm.answerList.length; i++) {
          if (index !== i) {
            this.postForm.answerList[i].isRight = false
          }
        }
      }
    },

    // 同步获得验证结果
    async validate() {
      return new Promise((resolve, reject) => {
        this.$refs.postForm.validate().then((valid) => {
          let check = true
          // 手动判断关键词给分
          if (this.postForm.quType === 'saq' && this.postForm.answerList && this.postForm.answerList.length>0) {
            for (let i = 0; i<this.postForm.answerList.length; i++) {
              const answer = this.postForm.answerList[i]
              if (answer.scoreRate <= 0) {
                check = false
                break
              }
            }
          }

          if (!check) {
            this.$message.error('给分比例必须>0且≤100')
            return
          }
          resolve(valid)
        })
      })
    },

    // 清理内容
    clear() {
      const quType = this.postForm.quType

      // 清理富文本
      this.$refs.content.setContent('')
      this.$refs.analysis.setContent('')

      // 重新选择
      this.handleTypeChange(quType)
    }
  }
}
</script>

<style scoped>

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  overflow: hidden;
  background-color: #969696;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 50px;
  height: 50px;
  margin: 0 8px 8px 0;
  display: inline-block;
}

::v-deep .el-upload--picture-card {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 50px;
  height: 50px;
  cursor: pointer;
  line-height: 55px;
  vertical-align: top;
}

.qt-alert{
  font-size: 12px;
  line-height: 18px;
  color: #ff3403;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
}
</style>
